<template>
  <a-menu
      class="app-menu"
      :open-keys.sync="openKeys"
      mode="inline"
      :openKeys="openKeys"
      :selectedKeys="current"
      @openChange="openChange"
      @click="changePage">
    <template v-for="item in $store.state.app.appMenuList" v-if="!item.hide">
      <a-menu-item v-if="!item.children" :key="item.name">
        <c-icon :icon="item.icon"/>
        <span>{{ item.title }}</span>
      </a-menu-item>
      <a-sub-menu v-else :key="item.name">
        <span slot="title">
          <c-icon :icon="item.icon"/>
          <span>{{ item.title }}</span>
        </span>
        <a-menu-item :key="subItem.name" v-for="subItem in item.children">
          {{ subItem.title }}
        </a-menu-item>
      </a-sub-menu>
    </template>
  </a-menu>
</template>

<script lang="js">
import routes from "@/router/routes";
import {findTree} from "@/utils/treeHandler";

export default {
  data() {
    return {
      current: [],
      openKeys: []
    };
  },
  watch: {
    $route() {
      if (!this.$store.state.app.appRoutePath.data) {
        this.changePage({key: this.$route.name})
      }
    }
  },
  created() {

  },
  methods: {
    changePage(e) {
      const findRes = findTree(this.$store.state.app.appMenuList, item => item.name === e.key);
      let path = `/${findRes.data.path}`;
      if (findRes.parent) path = `${findRes.parent.path}${path}`;
      this.$store.commit("setAppRoutePath", findRes);
      if (this.$route.path !== path) {
        this.$router.push(path)
      }
      this.setOpenKey(findRes)
    },
    openChange(e) {

    },
    setOpenKey(findRes) {
      if (findRes.parent) {
        this.openKeys = [findRes.parent['name']]
      }
      this.current = [findRes.data['name']]
    }
  }
}
</script>

<style scoped lang="stylus">
.app-menu {
  width 100%
  height 100%
}
</style>
